package xyz.chaobei.gateway;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import xyz.chaobei.gateway.initializer.HttpInitializer;

@Slf4j
public class HttpServer {

    private int port;

    private String proxy;

    public HttpServer(int port, String proxy) {
        this.port = port;
        this.proxy = proxy;
    }

    public void start() throws Exception {

        // 主从多线程模式
        EventLoopGroup bossGroup = new NioEventLoopGroup(3);
        EventLoopGroup workGroup = new NioEventLoopGroup(12);

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_RCVBUF, 32 * 1024)
                .childOption(ChannelOption.SO_SNDBUF, 32 * 1024)
                .childOption(EpollChannelOption.SO_REUSEPORT, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        serverBootstrap.group(bossGroup, workGroup);

        serverBootstrap.channel(NioServerSocketChannel.class)
                .childHandler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInitializer(proxy));

        Channel channel = serverBootstrap.bind(port).sync().channel();
        log.info("服务器已启动在：http://127.0.0.1:{},代理地址：{}", port, proxy);

        channel.closeFuture().sync();
    }

}
